import { Video, VideoProps, Image } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import clsx from 'clsx';
import { observer } from "mobx-react-lite";
import { ReactNode, useEffect, useRef, useState } from 'react';
import styles from './myVideo.module.less';
import playIconSVG from "./playIcon1.svg";
import myVideoStore from './myVideoStore';
import offAudioSVG from "./offAudio.svg";
import onAudioSVG from "./onAudio.svg";

interface Iprops extends VideoProps {
    children?: ReactNode,
    resetIndex?: number, // 当这个值变化时，暂停视频播放
    startPlay?: () => void;
    stopPlay?: () => void;
}

// 组件
const MyVideo = observer((props: Iprops) => {

    const dom = useRef<HTMLDivElement | null>(null);
    const video1Ctx = useRef<Taro.VideoContext | null>(null);
    const video2Ctx = useRef<Taro.VideoContext | null>(null);
    const playIconRef = useRef<HTMLImageElement | null>(null);
    const [width, setWidth] = useState<number>(100);
    const [height, setHeight] = useState<number>(100);
    const [videoWidth, setVideoWidth] = useState<number>(100);
    const [videoHeight, setVideoHeight] = useState<number>(100);
    const video1Id = useRef<string>(`videoBg-${Math.random().toString(36).substring(2, 9)}`);
    const video2Id = useRef<string>(`videoBg-${Math.random().toString(36).substring(2, 9)}`);
    const [playing, setPlaying] = useState(false);
    const [muted, setMuted] = useState(true);

    const { className, children, style, ...otherProps } = props;

    useEffect(() => {
        video1Ctx.current = Taro.createVideoContext(video1Id.current);
        video2Ctx.current = Taro.createVideoContext(video2Id.current);
    }, []);

    useDidShow(async () => {
        if (dom.current) {
            await new Promise(resolve => setTimeout(resolve, 100));
            const rect = await dom.current.getBoundingClientRect();
            if (rect) {
                console.log("--------------------useDidShow rect", rect);
                const scale = Math.min(rect.width / videoWidth, rect.height / videoHeight);
                setWidth(videoWidth * scale);
                setHeight(videoHeight * scale);
            }
        }
    });

    useEffect(() => {
        (async () => {
            if (video1Ctx.current && video2Ctx.current) {
                await new Promise(resolve => setTimeout(resolve, 100));
                video1Ctx.current.pause();
                video2Ctx.current.pause();
                props.stopPlay?.();
                // console.log("暂停播放");

            }
            if (playIconRef.current) {
                playIconRef.current.style.display = "none";
                await new Promise(resolve => setTimeout(resolve, 10));
                playIconRef.current.style.display = "block";
            }
            if (dom.current) {
                await new Promise(resolve => setTimeout(resolve, 100));
                const rect = await dom.current.getBoundingClientRect();
                if (rect) {
                    // console.log("--------------------useDidShow rect", rect);
                    const scale = Math.min(rect.width / videoWidth, rect.height / videoHeight);
                    setWidth(videoWidth * scale);
                    setHeight(videoHeight * scale);
                }
            }
        })();
    }, [props.resetIndex]);

    return (
        <div
            ref={dom}
            style={style as React.CSSProperties}
            className={clsx(styles.myVideo, className)}
        >
            <Video
                {...otherProps}
                className={styles.videoBg}
                initialTime={0}
                controls={false}
                autoplay={false}
                muted={true}
                loop={true}
                objectFit="fill"
                id={video1Id.current}
            />

            <div className={styles.videoMark}></div>

            <Video
                {...otherProps}
                id={video2Id.current}
                className={styles.videoFront}
                style={{ width, height }}
                initialTime={0}
                controls={false}
                autoplay={false}
                showCenterPlayBtn={false}
                loop={true}
                playBtnPosition="bottom"
                enableProgressGesture={false}
                autoPauseIfNavigate={true}
                muted={muted || myVideoStore.mute}
                // 视频准备完成后,获取视频的宽高
                onLoadedMetaData={async e => {
                    const { width, height } = e.detail;
                    if (width && height) {
                        setVideoWidth(width);
                        setVideoHeight(height);
                        if (dom.current) {
                            const rect = await dom.current.getBoundingClientRect();
                            if (rect) {
                                // console.log("-------------------------------rect", rect, { width, height });
                                const scale = Math.min(rect.width / width, rect.height / height);
                                setWidth(width * scale);
                                setHeight(height * scale);
                            }
                        }
                    }
                    if (video1Ctx.current && video2Ctx.current) {
                        await new Promise(resolve => setTimeout(resolve, 30));
                        video1Ctx.current.pause();
                        video2Ctx.current.pause();
                        props.stopPlay?.();
                        // console.log("暂停播放");
                    }
                }}
                onClick={(e) => {
                    console.log("onClick", e);
                    if (video1Ctx.current && video2Ctx.current) {
                        // 判断视频是否在播放中
                        if (playing) {
                            // setPlaying(false);
                            video1Ctx.current.pause();
                            video2Ctx.current.pause();
                            props.stopPlay?.();
                            // console.log("暂停播放");
                        } else {
                            // setPlaying(true);
                            video1Ctx.current.play();
                            video2Ctx.current.play();
                            if (props.startPlay) {
                                props.startPlay();
                            }
                            // console.log("播放视频");
                        }
                    }
                }}
                onPlay={async () => {
                    console.log("onPlay");
                    setMuted(false);
                    setPlaying(true);
                    if (playIconRef.current) {
                        playIconRef.current.style.display = "none";
                    }

                }}
                onPause={async () => {
                    console.log("onPause");
                    setPlaying(false);
                    if (playIconRef.current) {
                        playIconRef.current.style.display = "block";
                    }
                }}
            />

            {/* 播放按钮 */}
            <Image
                src={playIconSVG}
                ref={playIconRef}
                className={clsx(styles.playIcon)}
            />

            {/* 静音按钮 */}
            <Image
                src={myVideoStore.mute ? offAudioSVG : onAudioSVG}
                className={clsx(styles.audioIcon)}
                onClick={() => {
                    myVideoStore.setMute(!myVideoStore.mute);
                }}
            />

        </div>
    );
});

export default MyVideo;